#!/bin/bash

stty stop ''

cur_fil=${BASH_SOURCE[0]}
cur_dir=`dirname $cur_fil`
vim_dir=`dirname $cur_dir`

export PATH=$vim_dir/bin:$HOME/.local/bin:$PATH
export MXNET_GLUON_REPO=https://apache-mxnet.s3.cn-north-1.amazonaws.com.cn

[ -f /data/opt/env.sh ] && source /data/opt/env.sh
[ -f $cur_dir/fzf.bash ] && source $cur_dir/fzf.bash
[ -f ~/.tmp.bash ] && source ~/.tmp.bash

if [[ x$TAG_HOME == x ]]
then
    if [[ ! -d $HOME/.tags ]]
    then
        mkdir $HOME/.tags >/dev/null
    fi
    export TAG_HOME=$HOME/.tags
fi

alias xvimup='cd $vim_dir; git pull; cd - >/dev/null'
alias xbashrc='vim $cur_fil'
alias xvimrc='vim $vim_dir/vimrc'
alias xtmprc='vim ~/.tmp.bash'
alias xneta='netstat -ntpa'
alias xnetl='netstat -ntpl'

alias ll='ls -alF'
alias la='ls -A'
alias l='ls -CF'

alias sl='ls'
alias xrm='/bin/rm -i'
# alias sudo='sudo env PATH=$PATH'
alias grep='grep --color=auto --exclude-dir=.svn --exclude-dir=.git --exclude-dir=.tags --exclude=tags'

alias vi0='vim --noplugin'
alias xrs='sed -i "s/\s\+$//g" `find . -maxdepth 1 -type f `'

alias rvim='RSYNC=1 vim'
alias rgvim='RSYNC=1 vim -g'

########### Utils ############
alias frm='/bin/rm -rif'
alias rm='_rm'
_rm()
{
    trash_dir=/trash
    if [[ ! -d $trash_dir ]]
    then
        echo "no trash dir"
        return
    fi
    for file in $*
    do
        if [[ ${file:0:1} == '-' ]]
        then
            continue
        fi
        if [[ ${file:0:1} != "/" ]]
        then
            file=${PWD}/$file
        fi
        dir=$(dirname $file)
        if [[ ! -d $trash_dir/${dir} ]]
        then
            mkdir -p $trash_dir/${dir}
        fi
        mv $file $trash_dir/${dir}
    done
}

xpwd()
{
    tt=`pwd`
    if [[ x$(which xsel) == x ]]
    then
        echo $tt
        export tt
    else
        echo $tt | xsel
    fi
}

xps()
{
    if [[ x$1 == x ]]
    then
        ps H -eo pid,ppid,tid,%cpu,args --sort=%cpu
    else
        ps -eo pid,args | grep "$1" | grep -v grep
    fi
}

xgrep()
{
    exclude_dirs=
    tmp=$(pwd)/.grepignore
    if [[ -f $tmp ]]
    then
        exclude_files="{tags"
        exclude_dirs="{\.svn,\.git,\.tags"
        while read line
        do
            fty=`echo $line | cut -d\  -f1`
            pat=`echo $line | cut -d\  -f2`
            if [[ x$fty == xd ]] || [[ x$fty == x$pat ]]
            then
                exclude_dirs="${exclude_dirs},${pat}"
            else
                exclude_files="${exclude_files},${pat}"
            fi
        done < $tmp
        exclude_dirs="${exclude_dirs}}"
        exclude_files="${exclude_files}}"
    fi
    eval egrep --color=auto --exclude-dir=${exclude_dirs} -I -rin $*
}
########### Docker: gpasswd -a ${USER} docker; newgrp docker ###########

alias dst='docker stats'
alias dil='docker history'

docker()
{
    if [[ "${1}" = "tags" ]]
    then
        docker_tag_search $2;
    else
        command docker "$@";
    fi
}

docker_tag_search()
{
    image="$1"
    tags=`wget -q https://registry.hub.docker.com/v1/repositories/${image}/tags -O -  | sed -e 's/[][]//g' -e 's/"//g' -e 's/ //g' | tr '}' '\n'  | awk -F: '{print $3}'`
    if [ -n "$2" ]
    then
        tags=`echo "${tags}" | grep "$2" `
    fi
    echo "${tags}"
}

alias di='docker images'
alias dirma='docker rmi `docker images | grep  "<none>" | awk "{print $3}"` 2>/dev/null'
dirm()
{
    if [[ x$1 == x ]]
    then
        docker images
        echo -ne "\n[RM] Input ID: "
        read image
    else
        image=$@
    fi
    docker rmi $image
}

dii()
{
    if [[ x$1 == x ]]
    then
        docker images
        echo -ne "\n[INFO] Input ID: "
        read image
    else
        image=$@
    fi
    docker inspect $image
}

did()
{
    if [[ x$1 == x ]]
    then
        docker images
        echo -ne "\n[DEPEND] Input ID: "
        read image
    else
        image=$@
    fi
    docker image inspect --format='{{.RepoTags}} {{.Id}} {{.Parent}}' $(docker image ls -q --filter since=$image)
}

alias dc='docker container ls -a --format "table {{.ID}}\t{{.Image}}\t{{.Command}}\t{{.Status}}\t{{.Names}}"'
alias dcrma='docker container prune -f'
dcrm()
{
    if [[ x$1 == x ]]
    then
        docker container ls -a
        echo -ne "\n[RM] Input ID: "
        read container
    else
        container=$@
    fi
    # docker container kill --signal="SIGTERM" $container
    docker container stop $container
    docker container rm $container
}

dcc()
{
    if [[ x$1 == x ]]
    then
        docker container ls -a
        echo -ne "\n[INFO] Input ID: "
        read container
    else
        container=$@
    fi
    docker inspect $container
}

dcup()
{
    if [[ x$1 == x ]]
    then
        docker container ls -a
        echo -ne "\n[UP] Input ID: "
        read container
    else
        container=$@
    fi
    docker container start $container
}

dcdown()
{
    if [[ x$1 == x ]]
    then
        docker container ls -a
        echo -ne "\n[DOWN] Input ID: "
        read container
    else
        container=$@
    fi
    docker container stop $container
}

alias dv='docker volume ls'
alias dvrma='docker volume prune'
dvrm()
{
    if [[ x$1 == x ]]
    then
        docker volume ls
        echo -ne "\n[RM] Input ID: "
        read vols
    else
        vols=$@
    fi
    docker volume rm $vols
}

drun()
{
    args="-it"
    if [[ x$1 == xhelp ]]
    then
        echo "drun [host] [gpu] [sh] [image]"
        return
    fi
    if [[ x$1 == xhost ]]
    then
        args="$args --network host"
        shift
    fi
    if [[ x$1 == xgpu ]]
    then
        args="$args --runtime nvidia"
        shift
    fi
    if [[ x$1 == xsh ]]
    then
        # args="--rm $args --entrypoint /bin/bash"
        args="--rm $args"
        shift
    fi
    if [[ x$1 == x ]]
    then
        docker images
        echo -ne "\n[RUN] Input ID: "
        read image
    else
        image=$1
    fi
    if [[ x$image == x ]]
    then
        echo "Not input image id"
    else
        docker run $args $image
    fi
}

dsh()
{
    if [[ x$1 == x ]]
    then
        docker container ls
        echo -ne "\n[SH] Input ID: "
        read container
    else
        container=$1
    fi
    if [[ x$container == x ]]
    then
        return
    fi
    docker exec -it $container bash
}

dlog()
{
    if [[ x$1 == x ]]
    then
        docker container ls
        echo -ne "\n[LOG] Input ID: "
        read container
    else
        id=$1                                                                                       
        if [[ ${#id} -le 2 ]]
        then
            container=`docker container ls -a --format "{{.ID}}" | head -n $id | tail -n 1`
        else
            container=$1
        fi
    fi
    if [[ x$container == x ]]
    then
        return
    fi
    logfile=`docker inspect --format='{{.LogPath}}' $container`
    logbase=`basename $logfile`
    if [[ x$2 == x ]]
    then
        echo -ne "[LOG] Clear $logbase (Y/n): "
        read result
    else
        result=$2
    fi
    if [[ x$result != xN ]] && [[ x$result != xn ]]
    then
        sudo truncate -s 0 $logfile
    fi
    docker logs --follow $container
}

dexe()
{
    args=($@)
    container=$1
    if [ "${#container}" -eq "12" ]
    then
        bashcmd=${args[@]: 1:$#}
        docker exec $container bash -c "$bashcmd"
    else
        docker container ls
        echo -ne "\n[SH] Input ID: "
        read container
        echo ""
        docker exec $container bash -c "$@"
    fi
}

dip()
{
    container=$1
    if [ "${#container}" -ne "12" ]
    then
        docker container ls
        echo -ne "\n[IP] Input ID: "
        read container
    fi
    if [[ x$container == x ]]
    then
        return
    fi
    docker inspect --format="{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}" $container
}

dmount()
{
    container=$1
    if [ "${#container}" -ne "12" ]
    then
        docker container ls
        echo -ne "\n[MOUNT] Input ID: "
        read container
    fi
    if [[ x$container == x ]]
    then
        return
    fi
    jsontool=`which jq`
    if [[ x$jsontool == x ]]
    then
        jsontool=python -m json.tool
    fi
    docker inspect -f '{{ json .Mounts }}' $container | $jsontool
}

dcst()
{
    if [[ x$1 == x ]]
    then
        docker container ls
        echo -ne "\n[STAT] Input ID: "
        read container
    else
        container=$@
    fi
    docker stats --no-stream $container
}

dcrmk12()
{
    filters=
    if [[ x$1 != x ]]
    then
        filters="${filters} --filter label=k12ai.service.user=$1"
    fi
    if [[ x$2 != x ]]
    then
        filters="${filters} --filter label=k12ai.service.uuid=$2"
    fi
    if [[ x$filters != x ]]
    then
        for c in `docker container ls -a ${filters} --format "{{.ID}}"`
        do
            docker container stop $c > /dev/null
            docker container rm $c
        done
    else
        echo "dcrmk12 user uuid"
    fi
}
